import QtQuick 1.1
import "main.js" as Engine

MyPage {
    id: mucPage

    /************************************************************/
    colorPage: "white"

    property string avatarPic: ""
    //property string resourceJid: ""

    Connections {
        target: muc

        onParticipantChanged: {
            console.log("QML: XmppMuc::onParticipantChanged(): " + nickName)
        }

        onParticipantAdded: {
            console.log("QML: XmppMuc::onParticipantAdded(): " + nickName)
            listModelParticipants.append( { jid:nickName } )
        }

        onParticipantRemoved: {
            console.log("QML: XmppMuc::onParticipantRemoved(): " + nickName)
            for( var x=0; x<listModelParticipants.count; x++)
            {
                var name = listModelParticipants.get(x).jid
                if( name == nickName ) {
                    listModelParticipants.remove( x )
                    break
                }
            }
        }
    }

    Component.onCompleted: {
        /* разблокировка ориентации */
        main.appOrientation = main.orAuto

        /* инициализация muc объекта текущим jid-ом комнаты  */
        muc.jidRoom = xmppClient.chatJid

        /* открываем чат и инициализируем список сообщениями
         * которые были ранее с этим собеседником */
        xmppClient.openChat( xmppClient.chatJid )

        /* запрашиваем его аватарку */
        //avatarPic = xmppClient.getAvatarByJid( xmppClient.chatJid )

        /* если последнее сообщение было от собеседника чата
         * то инициализируем ресурс mucPage.resourceJid
         * ресурсом его последнего сообщения */
        /*if( xmppClient.bareJidLastMsg == xmppClient.chatJid ) {
            mucPage.resourceJid = xmppClient.resourceLastMsg
        }*/

        var listParticipants = muc.getParticipants( )
        listModelParticipants.clear();
        /* инициализация списка собеседников чата */
        for( var z=0; z<listParticipants.length; z++ )
        {
            //console.log( "Participant:["+listParticipants[z]+"]" )
            if( listParticipants[z] == "" ) { continue; }
            listModelParticipants.append( { jid:listParticipants[z] } )
        }
    }

    /**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**/
    Component {
        id: componentWrapperItem

        Rectangle {
            id: wrapper
            border.color: msgResource === muc.nickName ? "blue" : Engine.getNameColor( msgResource )
            color: msgResource === muc.nickName ? "white" : "lightblue"
            radius: 10
            property string text: msgText
            clip: true

            anchors.horizontalCenter: parent.horizontalCenter

            MouseArea {
                id: maMsg
                anchors.fill: parent
                onPressAndHold: {
                    // цитирование
                    animCit.start()
                    txtMessage.text += "> \"" + mainSmiles.htmlToPlainText( wrapper.text ) + "\"\n"
                    //txtMessage.text += "> \"" + wrapper.text + "\"<br/>"
                }
                onClicked: {
                    wrapper.ListView.view.currentIndex = index
                }
            }

            ListView.onAdd: ParallelAnimation {
                NumberAnimation {
                    target: wrapper
                    property: "opacity"
                    from: 0; to: 1
                    duration: 100
                    easing.type: Easing.InOutQuad
                }
                NumberAnimation {
                    target: wrapper;
                    property: "scale";
                    duration: 200;
                    from: 0.1; to: 1
                    easing.type: Easing.InOutQuad
                }
            }

            Image {
                id: imgDlr
                //anchors.left: parent.left;
                //anchors.leftMargin: 10
                anchors.bottom: parent.bottom; anchors.bottomMargin: 10
                source: msgResource === muc.nickName ? "qrc:/qml/images/msg_recv.png" : ( msgDlr === true ? "qrc:/qml/images/msg_dlr.png" : "qrc:/qml/images/msg_sent.png")
                height: 32
                width: 32
                smooth: true
                Component.onCompleted: {
                    if( msgResource === muc.nickName ) {
                        imgDlr.anchors.right = parent.right
                        imgDlr.anchors.rightMargin = 10
                    } else {
                        imgDlr.anchors.left = parent.left
                        imgDlr.anchors.leftMargin = 10
                    }
                }
            }

            Image {
                id: imgAvatar
                smooth: true
                height: 32
                width: 32
                anchors.top: parent.top; anchors.topMargin: 10
                //source: msgMy === true ? "qrc:/qml/images/avatar.png" : (main.chatAvatar === "" ? "qrc:/qml/images/avatar.png" : main.chatAvatar)
                source: msgResource === muc.nickName ? "qrc:/qml/images/avatar.png" : (avatarPic === "" ? "qrc:/qml/images/avatar.png" : avatarPic)
                Image {
                    anchors.centerIn: parent
                    height: parent.height
                    width: parent.width
                    smooth: true
                    source: msgResource === muc.nickName ? "qrc:/qml/images/meego_frame_32w.png" : "qrc:/qml/images/meego_frame_32b.png"
                }
                Component.onCompleted: {
                    if( msgResource === muc.nickName ) {
                        imgAvatar.anchors.right = parent.right
                        imgAvatar.anchors.rightMargin = 10
                    } else {
                        imgAvatar.anchors.left = parent.left
                        imgAvatar.anchors.leftMargin = 10
                    }
                }
            }

            Text {
                id: txtHeader
                anchors.top: parent.top; anchors.topMargin: 10
                anchors.left: msgResource === muc.nickName ? parent.left : imgDlr.right; anchors.leftMargin: 10
                text: msgResource === muc.nickName ? "[" + msgDateTime + "] :" : "[" + msgDateTime + "]  " + /*xmppClient.chatJid + "/" + */msgResource + ":"
                font.pixelSize: 16
                opacity: 0.8
                color: msgResource === muc.nickName ? "blue" : Engine.getNameColor( msgResource )
                font.italic: true
                visible: (msgResource !== muc.nickName) && ( msgResource == "" ) ? false : true
            }

            Text {
                id: text_field
                anchors.left: msgResource === muc.nickName ? parent.left : imgDlr.right; anchors.leftMargin: 10
                anchors.right: msgResource === muc.nickName ? imgDlr.left : parent.right; anchors.rightMargin: 10
                anchors.top: txtHeader.bottom; anchors.topMargin: 5
                anchors.bottom: parent.bottom; anchors.bottomMargin: 10
                text: wrapper.text
                wrapMode: Text.WrapAtWordBoundaryOrAnywhere
                font.pixelSize: 20
                textFormat: Text.RichText
                onLinkActivated: {
                    Qt.openUrlExternally (link)
                }
                font.bold: (msgResource !== muc.nickName) && ( msgResource == "" ) ? true : false
            }

            width: listViewMessages.width - 10
            //height: text_field.paintedHeight + text_field.anchors.topMargin + text_field.anchors.bottomMargin + txtHeader.height + txtHeader.anchors.topMargin
            height: text_field.paintedHeight + text_field.anchors.topMargin + text_field.anchors.bottomMargin + txtHeader.height + txtHeader.anchors.topMargin <
                    imgDlr.height+imgDlr.anchors.bottomMargin + imgAvatar.height + imgAvatar.anchors.topMargin ?
                        imgDlr.height+imgDlr.anchors.bottomMargin + imgAvatar.height + imgAvatar.anchors.topMargin :
                        text_field.paintedHeight + text_field.anchors.topMargin + text_field.anchors.bottomMargin + txtHeader.height + txtHeader.anchors.topMargin


            SequentialAnimation {
                id: animCit
                NumberAnimation { target: wrapper; property: "rotation"; to:  0.8; duration: 35 }
                NumberAnimation { target: wrapper; property: "rotation"; to: -0.8; duration: 70 }
                NumberAnimation { target: wrapper; property: "rotation"; to:  0; duration: 30 }
                loops: 3
                alwaysRunToEnd: true
            }
            Component.onCompleted: {
                // парсинг на смайлы в сообщении
                wrapper.text = mainSmiles.parseMsgString( wrapper.text )
            }

            states: State {
                name: "Current"
                when: (wrapper.ListView.isCurrentItem )
                //PropertyChanges { target: posGr1; position: 0 }
            }

            transitions: Transition {
                //NumberAnimation { properties: "position"; duration: 300 }
            }
        }

    } //Component

    /**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-**/


    /* --------------------( ресурсы jid )-------------------- */
    ListModel {
        id: listModelParticipants
    }


    /*--------------------(верхняя панелька с отображение информации о jid)--------------------*/

    property bool flSendMsg: false


    /* ------------( подписка на сигналы muc объекта )------------ */
    Connections {
        target: muc

        /*onMessageReceived: {
        }*/
    }

    function strTopPanel( isTyping, showTyping )
    {
        var ret = xmppClient.chatJid
        /*if(mucPage.resourceJid != "") {
            ret += "/" + mucPage.resourceJid
        }*/
        return ret;
    }


    /* панелька с надписью jid */
    Rectangle {
        id: topPanelChat
        z: 11
        width: parent.width
        height: 40
        color: "black"
        anchors.top: parent.top;
        anchors.left: parent.left;
        visible: main.inPortrait

        gradient:  gr1
        Gradient {
            id: gr1
            GradientStop { position: 0; color: "#3f3f3f" }
            GradientStop { position: 1; color: "#000000" }
        }
        Gradient {
            id: gr2
            GradientStop { position: 0; color: "#000000" }
            GradientStop { position: 1; color: "#3f3f3f" }
        }

        Image {
            id: imgPresence
            anchors.left: parent.left; anchors.leftMargin: 10
            anchors.verticalCenter: parent.verticalCenter
            height: topPanelChat.height - 10
            width: height
            source: "qrc:/qml/images/muc.png"
        }
        Text {
            id: txtPresence
            anchors.left: imgPresence.right; anchors.leftMargin: 10
            anchors.verticalCenter: parent.verticalCenter
            color: "white"
            font.pixelSize: parent.height/2.5
            text: strTopPanel( false, false )
        }
        Image {
            id: imgDownArrow
            source: "qrc:/qml/images/small_arrow_black.png"
            anchors.right: parent.right; anchors.rightMargin: 15
            smooth: true
            rotation: -90
        }

        MouseArea {
            anchors.fill: parent
            onClicked: {
                if(panelListResources.state == "hidden") {
                    panelListResources.state = "visible"
                } else {
                    panelListResources.state = "hidden"
                }
            }
            onPressedChanged: {
                if(pressed) {
                    topPanelChat.gradient = gr2
                } else {
                    topPanelChat.gradient = gr1
                }
            }
        }
    }

    /* -----------------( выпадающая панелька с участниками чата )----------------- */
    Rectangle {
        id: panelListResources
        z: 10
        clip: true
        anchors.left: parent.left
        width: parent.width
        height: 350
        color: "black"
        opacity: 0.8
        state: "hidden"
        states: [
            State {
                name: "hidden"
                AnchorChanges{ target: panelListResources; anchors.bottom: mucPage.top }
                PropertyChanges { target: imgDownArrow ; rotation: -90 }
            },
            State {
                name: "visible"
                AnchorChanges{ target: panelListResources; anchors.top: topPanelChat.bottom }
                PropertyChanges { target: imgDownArrow ; rotation: 90 }
            }
        ]
        transitions: Transition {
            ParallelAnimation {
                AnchorAnimation { duration: 400; easing.type: Easing.InOutQuad }
                PropertyAnimation { duration: 400; property: "rotation" }
            }
        }
        ListView {
            id: listViewResources
            anchors.top: parent.top
            anchors.left: parent.left
            width: parent.width
            height: parent.height - bottomPanel.height
            model: listModelParticipants
            clip: true
            delegate: Component {
                Rectangle {
                    id: itemResource
                    height: 70
                    width: panelListResources.width
                    color: "transparent"
                    border.color: "gray"
                    radius: 5
                    Text {
                        id: textResource
                        text: jid
                        font.pixelSize: itemResource.height/2
                        anchors.horizontalCenter: parent.horizontalCenter
                        anchors.verticalCenter: parent.verticalCenter
                        color: "white"
                        font.bold: false
                    }
                    states: State {
                        name: "Current"
                        when: itemResource.ListView.isCurrentItem
                        PropertyChanges { target: itemResource; color: "gray" }
                    }
                    MouseArea {
                        anchors.fill: parent
                        onClicked: {
                            itemResource.ListView.view.currentIndex = index

                            txtMessage.text = jid + ": " + txtMessage.text
                            panelListResources.state = "hidden"
                        } //onClicked
                    } //MouseArea
                }
            } //Component
        }
        Rectangle {
            id: bottomPanel
            anchors.left: parent.left
            anchors.bottom: parent.bottom
            width: parent.width
            height: 25
            gradient: Gradient {
                GradientStop { position: 0; color: "gray" }
                GradientStop { position: 0.5; color: "black" }
                GradientStop { position: 1; color: "gray" }
            }
            MouseArea {
                anchors.fill: parent
                onClicked: {
                    panelListResources.state = "hidden"
                }
            }
        }
    }

    /* --------------------(список сообщений)-------------------- */
    ListView {
        id: listViewMessages
        anchors.top: main.inPortrait == true ? topPanelChat.bottom : parent.top
        anchors.topMargin: 5
        anchors.bottom: panelWriteText.top; anchors.bottomMargin: 5
        anchors.left: parent.left;// anchors.leftMargin: 5
        anchors.right: parent.right;// anchors.rightMargin: 5
        clip: true
        model: xmppClient.messages
        delegate: componentWrapperItem
        spacing: 5
        onCountChanged: {
            listViewMessages.positionViewAtIndex(count - 1, ListView.Beginning)
        }
        onHeightChanged: {
            listViewMessages.positionViewAtIndex(count - 1, ListView.Beginning)
        }
    }


    /*--------------------(панелька с вводом текста)--------------------*/
    Rectangle {
        id: panelWriteText
        height: 100
        anchors.bottom: main.inPortrait == true ? toolBar.top : parent.bottom;
        anchors.left: parent.left;
        anchors.right: parent.right;
        color: "gray"

        Rectangle {
            id: wrapperTextEdit
            anchors.bottom: parent.bottom; anchors.bottomMargin: 5
            anchors.left: parent.left; anchors.leftMargin: 5
            anchors.right: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? wrapperImgSmiles.left : wrapperImgSend.left
            anchors.top: parent.top; anchors.topMargin: 5
            //border.color: "blue"
            //border.width: 2
            color: "transparent"
            radius: 8
            clip: true
            Flickable {
                id: flickMsg
                anchors.fill: parent
                contentHeight: txtMessage.height
                contentWidth: txtMessage.width
                flickableDirection: Flickable.VerticalFlick
                clip: true
                function ensureVisible(r)
                {
                    if (contentX >= r.x)
                        contentX = r.x;
                    else if (contentX+width <= r.x+r.width)
                        contentX = r.x+r.width-width;
                    if (contentY >= r.y)
                        contentY = r.y;
                    else if (contentY+height <= r.y+r.height)
                        contentY = r.y+r.height-height;
                }

                MyTextEdit2 {
                //MyTextEdit {
                    id: txtMessage
                    wrapMode: TextEdit.Wrap
                    font.pixelSize: 22
                    textFormat: TextEdit.PlainText
                    //textFormat: TextEdit.RichText
                    width: flickMsg.width
                    height: flickMsg.height
                    //onCursorRectangleChanged: flickMsg.ensureVisible( cursorRectangle )
                    onTextChanged: {
                    }
                }

            }
        } //wrapperTextEdit


        /* кнопка смайлов для вертикальной ориентации */
        Rectangle {
            id: wrapperImgSmiles
            visible: screen.orientationString == "Landscape" || screen.orientationString == "LandscapeInverted" ? true : false
            height: 100
            width: 100
            anchors.right:wrapperImgSend.left
            anchors.verticalCenter: parent.verticalCenter
            color: "transparent"
            Image {
                id: imgFramePressSmiles
                source: "qrc:/qml/images/bar_glow.png"
                width: imgSmilesMsg.width + 2
                height: imgSmilesMsg.height + 2
                anchors.centerIn: parent
                smooth: true
                opacity: 0
                Behavior on opacity { NumberAnimation { duration: 150 } }
            }
            Image {
                id: imgSmilesMsg
                anchors.centerIn: parent
                source: "qrc:/qml/images/bar_smiles.png"
                height: 96
                width: 96
                smooth: true
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        dlgSmiles.dlgShowHide()
                    }
                    onPressedChanged: {
                        if( pressed ) {
                            imgFramePressSmiles.opacity = 1
                        } else  {
                            imgFramePressSmiles.opacity = 0
                        }
                    }
                }
            }
        } //wrapperImgSend


        /* копка отправки сообщения */
        Rectangle {
            id: wrapperImgSend
            height: 100
            width: 100
            anchors.right:parent.right
            //anchors.rightMargin: 5
            anchors.verticalCenter: parent.verticalCenter
            color: "transparent"
            Image {
                id: imgFramePress
                source: "qrc:/qml/images/bar_glow.png"
                width: imgSendMsg.width + 2
                height: imgSendMsg.height + 2
                anchors.centerIn: parent
                smooth: true
                opacity: 0
                Behavior on opacity { NumberAnimation { duration: 150 } }
            }
            Image {
                id: imgSendMsg
                anchors.centerIn: parent
                source: "qrc:/qml/images/msg_send.png"
                MouseArea {
                    anchors.fill: parent
                    onClicked: {
                        var ret = muc.sendMessage( txtMessage.text )
                        if( ret ) {
                            flSendMsg = true
                            txtMessage.text = ""
                            flSendMsg = false
                            //notify.notifyMessageSent() //TODO:
                        }
                    }
                    onPressedChanged: {
                        if( pressed ) {
                            imgFramePress.opacity = 1
                        } else  {
                            imgFramePress.opacity = 0
                        }
                    }
                }
            }
        } //wrapperImgSend
    } //panelWriteText


    /********************************( Toolbar )************************************/

    ToolBar {
        id: toolBar

        visible: main.inPortrait

        /****/
        ToolButton {
            id: toolBarButtonRoster
            icon: "qrc:/qml/images/bar_roster.png"
            anchors.left: parent.left
            anchors.leftMargin: (0.5*(parent.width/4) - 0.5*toolBarButtonRoster.width)
            onClicked: {
                mucPage.closePage( "qrc:/qml/RosterPage.qml" )
                xmppClient.resetUnreadMessages( xmppClient.chatJid ) //сброс непрочитанных сообщ.
            }
            pauseAnim: 500
        }
        ToolButton {
            id: toolBarButtonChats
            icon: "qrc:/qml/images/bar_open_chats.png"
            anchors.left: parent.left
            anchors.leftMargin: (1.5*(parent.width/4) - 0.5*toolBarButtonChats.width)
            onClicked: {
                mucPage.closePage( "qrc:/qml/ChatsPage.qml" )
                xmppClient.resetUnreadMessages( xmppClient.chatJid ) //сброс непрочитанных сообщ.
            }
            pauseAnim: 600
        }
        ToolButton {
            id: toolBarButtonSmiles
            icon: "qrc:/qml/images/bar_smiles.png"
            anchors.left: parent.left
            anchors.leftMargin: (2.5*(parent.width/4) - 0.5*toolBarButtonSmiles.width)
            onClicked: {
                dlgSmiles.dlgShowHide()
            }
            pauseAnim: 700
        }
        ToolButton {
            id: toolBarButtonOptions
            icon: "qrc:/qml/images/bar_options.png"
            anchors.left: parent.left
            anchors.leftMargin: (3.5*(parent.width/4) - 0.5*toolBarButtonOptions.width)
            onClicked: {
                dlgMsgOptions.dlgShowHide()
            }
            pauseAnim: 800
        }
    }
    /*********************************************************************/

    /*-------------------( смайлы )-------------------*/
    DialogSmiles {
        id: dlgSmiles
        title: "Smiles"
        smilesModel: mainSmiles.smilesModel
        onSmileSelected: {
            txtMessage.text += dlgSmiles.selectedSmile
        }
    }

    /*----------------------( опции чата )----------------------*/
    DialogMucOptions {
        id: dlgMsgOptions
        onItemClicked: {
            if( itemSelected == "clearChat" ) {
                xmppClient.clearChat( xmppClient.chatJid )
            } else if( itemSelected == "" ) {
            }
        }
    }
}
